package org.lex.notepad.ui;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.lex.notepad.ui.status.StatusBar;
import org.lex.notepad.ui.status.StatusPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NotepadContenetPane extends JPanel {
	private Logger log = LoggerFactory.getLogger(NotepadContenetPane.class);

	private NotepadEditor editor = null;
	private StatusPane statusPane = null;

	public NotepadContenetPane() {
		super(new BorderLayout());
		this.initialize();
		this.loadConfigurations();
	}

	private void loadConfigurations() {
		// XMLConfig cfg = Config.instance();
		// /*
		// * load editor configuration
		// */
		// //tabsize
		// this.getEditor();
		// editor.setTabSize( Integer.parseInt( cfg.getString(
		// CK.EDITOR_TAB_SIZE )
		// ) );
		// //font
		// editor.setFont( cfg.getFont( CK.EDITOR_FONT ) );
		// //color
		// editor.setBackground( cfg.getColor( CK.EDITOR_BACKGROUND ) );
		// editor.setForeground( cfg.getColor( CK.EDITOR_TEXT_COLOR ) );
		// editor.setSelectionColor( cfg.getColor( CK.EDITOR_SELECTION_COLOR )
		// );
		// //wrap
		// editor.setLineWrap( cfg.getBoolean( CK.EDITOR_WRAP_LINE ) );
		// editor.setWrapStyleWord( cfg.getBoolean( CK.EDITOR_WRAP_WORD ) );
		// //charset
		// editor.setCharset( cfg.getCharset( CK.EDITOR_ENCODING ) );
		// /*
		// * status bar
		// */
		// statusPane.setPosition( 0, 0, 100 );
		// statusPane.setFileFormat( Utilities.parseOSFromLineSeperator(
		// SystemProperties.lineSeparator() ) );
		// statusPane.setCharset( cfg.getCharset( CK.EDITOR_ENCODING ) );
	}

	public NotepadEditor getEditor() {
		if (editor == null) {
			editor = new NotepadEditor();
			editor.getCaret().addChangeListener(new ChangeListener() {
				StatusBar status = getStatusBar();

				public void stateChanged(ChangeEvent e) {
					try {
						int pos = editor.getCaretPosition();
						int line = editor.getLineOfOffset(pos);
						int column = pos - editor.getLineStartOffset(line);
						status.setPosition(++line, column);
					} catch (Exception ex) {
						log.error("calculate caret position failed", ex);
					}
				}
			});
		}
		return editor;
	}

	public StatusBar getStatusBar() {
		return this.getStatusPane();
	}

	private void initialize() {
		this.add(new JScrollPane(this.getEditor()), BorderLayout.CENTER);
		this.add(getStatusPane(), BorderLayout.SOUTH);
	}

	private StatusPane getStatusPane() {
		if (null == statusPane)
			statusPane = new StatusPane();
		return statusPane;
	}
}
